//
//  EFQcodePayEndViewController.m
//  EnjogFood
//
//  Created by 王芳 on 17/5/16.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFQcodePayEndViewController.h"
#import "EFQuickQcodeOrderView.h"
#import "RHCQRScanViewController.h"
#import "EFSepecialItem.h"
#import "iToast.h"
#import "EFShoppingCartViewController.h"
#import "EFShoppingCartItem.h"

@interface EFQcodePayEndViewController ()<RHCQRScanViewControllerDelegate>

@property (strong, nonatomic) EFQuickQcodeOrderView *qcodeView;
@property (strong, nonatomic) NSMutableArray *cartProductArray;

@property (strong, nonatomic) UIImageView *topViewNoQcode;
@property (strong, nonatomic) UIView *circleView;
@property (strong, nonatomic) UIImageView *circleImageV;
@property (strong, nonatomic) UILabel *circleLabel;
@property (strong, nonatomic) UILabel *scanLabel;

@property (strong, nonatomic) UIImageView *scanImageV; //fuceng_image_scancode
@property (strong, nonatomic) UIImageView *scanLine;
@property (assign, nonatomic) BOOL isStopScan;
@property (assign, nonatomic) BOOL isScan;
@property (assign, nonatomic) CGFloat scanStartPos;
@property (assign, nonatomic) CGFloat scanEndPos;
@property (strong, nonatomic) dispatch_queue_t movePlateQueue;
@property (strong, nonatomic) RHCQRScanViewController *scanController;

@property (strong, nonatomic) UIView *rightBtnView;
@property (strong, nonatomic) UIButton *scanBtn;
@property (strong, nonatomic) UIButton *shopCartBtn;

@end

@implementation EFQcodePayEndViewController

- (instancetype)init{
    self = [super init];
    if (self) {
        self.isScan = NO;
        self.isStopScan = NO;
        self.movePlateQueue = dispatch_queue_create("movePlates", NULL);
        self.title = @"快速结账";
        self.scanStartPos = 70 - 44;
        self.scanEndPos = 210;
    }
    return self;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self backToView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
   // [self.navigationController.navigationBar setBackgroundImage:IMG(@"Rectangle 9") forBarMetrics:UIBarMetricsDefault];
    self.view.backgroundColor = [UIColor whiteColor];
    self.cartProductArray = [[NSMutableArray alloc] init];
    // Do any additional setup after loading the view.
   
    //右按钮
    [self.rightBtnView addSubview:self.scanBtn];
    [self.rightBtnView addSubview:self.shopCartBtn];
    self.scanBtn.left = 0;
    self.shopCartBtn.left = self.scanBtn.right + 13;
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBtnView];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    
    //shop cart
    [self.view addSubview:self.qcodeView];
    self.qcodeView.top = 354;//self.bottomeView.top;
    
    //topView
    [self.view addSubview:self.topViewNoQcode];
    self.topViewNoQcode.userInteractionEnabled = YES;
    [self.topViewNoQcode addSubview:self.circleView];
    self.circleView.top = 95;
    self.circleView.left = (kScreenWidth - self.circleView.width)/2;
    
    [self.circleView addSubview:self.circleImageV];
    self.circleImageV.top = 20;
    self.circleImageV.left = (self.circleView.width - self.circleImageV.width)/2;
    [self.circleView addSubview:self.circleLabel];
    self.circleLabel.center = CGPointMake(self.circleImageV.centerX, self.circleImageV.bottom + 8);
    self.circleLabel.top = self.circleImageV.bottom + 8;
    
    [self.topViewNoQcode addSubview:self.scanLabel];
    self.scanLabel.top = self.circleView.bottom + 19;
    self.scanLabel.left = (kScreenWidth - self.scanLabel.width)/2;
    
    
    //topScanView
    [self.view addSubview:self.scanImageV];
    [self.scanImageV addSubview:self.scanLine];
    self.scanLine.left = 20;
    self.scanImageV.hidden = YES;
    
   
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getShopCartData];
    [self.qcodeView setObject:APP_CONTEXT.shoppingCartManager.scanProductsCart];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIButton *)scanBtn{
    if (!_scanBtn) {
        _scanBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 23)];
        [_scanBtn setImage:IMG(@"nav_code2") forState:UIControlStateNormal];
        [_scanBtn addTarget:self action:@selector(scanBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _scanBtn;
}

- (UIButton *)shopCartBtn{
    if (!_shopCartBtn) {
        _shopCartBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
        [_shopCartBtn setImage:IMG(@"nav_icon_shoppingcart_default") forState:UIControlStateNormal];
        [_shopCartBtn addTarget:self action:@selector(shopCart) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shopCartBtn;
}

- (UIView *)rightBtnView{
    if (!_rightBtnView) {
        _rightBtnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 22)];
        _rightBtnView.backgroundColor = [UIColor whiteColor];
    }
    return _rightBtnView;
}


- (EFQuickQcodeOrderView *)qcodeView{
    if (!_qcodeView) {
        _qcodeView = [[EFQuickQcodeOrderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 197)];
    }
    return _qcodeView;
}

- (UIImageView *)topViewNoQcode{
    if (!_topViewNoQcode) {
        _topViewNoQcode = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 354)];
        _topViewNoQcode.image = IMG(@"bg_image_quicksettle");
       
    }
    return _topViewNoQcode;
}

- (UIView *)circleView{
    if (!_circleView) {
        _circleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        _circleView.backgroundColor = RGBCOLOR(0x69ba45);
        _circleView.layer.cornerRadius = 50;
        _circleView.clipsToBounds = YES;
        _circleView.userInteractionEnabled = YES;
         [_circleView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scanBtnClick)]];
    }
    return _circleView;
}

- (UIImageView *)circleImageV{
    if (!_circleImageV) {
        _circleImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
        _circleImageV.image = IMG(@"nav_scancode_icon__default");
    }
    return _circleImageV;
}

- (UILabel *)circleLabel{
    if (!_circleLabel) {
        _circleLabel = [[UILabel alloc] init];
        _circleLabel.font = [UIFont systemFontOfSize:10];
        _circleLabel.textColor = [UIColor whiteColor];
        _circleLabel.text = @"扫一扫\n商品条形码";
        _circleLabel.numberOfLines = 0;
        _circleLabel.textAlignment = NSTextAlignmentCenter;
        [_circleLabel sizeToFit];
        _circleLabel.backgroundColor = [UIColor clearColor];
    }
    return _circleLabel;
}

- (UILabel *)scanLabel{
    if (!_scanLabel) {
        _scanLabel = [[UILabel alloc] init];
        _scanLabel.font =[UIFont systemFontOfSize:15];
        _scanLabel.textColor = kBlack666;
        _scanLabel.text = @"请扫二维码或者条形码添加商品";
        [_scanLabel sizeToFit];
    }
    return _scanLabel;
}

- (UIImageView *)scanImageV{
    if (!_scanImageV) {
        _scanImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 354)];
        _scanImageV.image = IMG(@"Combined Shape");
    }
    return _scanImageV;
}

- (UIImageView *)scanLine{
    if (!_scanLine) {
        _scanLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 335, 40)];
        _scanLine.image = IMG(@"larger_image_scancode");
    }
    return _scanLine;
}

- (RHCQRScanViewController *)scanController{
    if (!_scanController) {
        _scanController = [[RHCQRScanViewController alloc] init];
        
    }
    return _scanController;
}

//-(UIStatusBarStyle)preferredStatusBarStyle{
//    return UIStatusBarStyleLightContent;
//}

- (void)backToView{
   // [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    self.topViewNoQcode.hidden = NO;
    self.scanImageV.hidden = YES;
    //self.rightBtnView.hidden = NO;
}

- (void)scanBtnClick{
    //切换到扫描页面
    if (self.isScan) {
        self.isScan = NO;
        [self backToView];
    }else{
        self.navigationItem.title = @"扫码";
        self.topViewNoQcode.hidden = YES;
        self.scanImageV.hidden = NO;
        self.scanController.view.frame = self.topViewNoQcode.frame;
        [self.view insertSubview:self.scanController.view atIndex:0];
        self.scanController.delegate = self;
        [self startScan];
    }
  
}

- (void)scanLineMove{
    [self.scanLine setHidden:NO];
    self.isStopScan = NO;
    self.isScan = YES;
    
    dispatch_async(self.movePlateQueue, ^{
        while (1) {
            if (!self.scanLine || self.isStopScan) {
                return;
            }
            CGPoint oldPoint = self.scanLine.frame.origin;
            float x = oldPoint.x;
            float y = oldPoint.y;
            if (y > self.scanEndPos) {
                y = self.scanStartPos;
            }
            CGPoint newPoint = CGPointMake(x, y + 0.5);
            dispatch_async(dispatch_get_main_queue(), ^{
                CGRect temp = self.scanLine.frame;
                temp.origin = newPoint;
                self.scanLine.frame = temp;
            });
            usleep(10000);
            
        }
    });
}

- (void)stopScanLine{
    self.scanLine.hidden = YES;
    self.isStopScan = YES;
    self.isScan = NO;
}

- (void)startScan{
    [self.scanController startRunning];
    if (!self.isScan) {
        [self scanLineMove];
    }
}

- (void)stopScan{
    [self.scanController stopRunning];
    if (self.isScan) {
        [self stopScanLine];
    }
}


#pragma mark - RHCQRcodeViewControllerDelegate

- (void)didReceiveQRCode:(NSString *)resultUrl
{
    if (resultUrl) {
        [self showHUD];
        [self getScanInfo:resultUrl];
        [self stopScan];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self backToView];
        });
        
    }
}

- (void)getScanInfo:(NSString *)str{
    __weak typeof(self) weakSelf = self;
    
    [APP_CONTEXT.net getFastCheckoutProduct:str OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        self.HUD.hidden = YES;
        
        if (code == 0) {
            EFSepecialItem *product = [EFSepecialItem yy_modelWithDictionary:info];
            product.qty = [NSNumber numberWithInt:1];
            //加入购物车
            [APP_CONTEXT.shoppingCartManager addToScanProduct:product];
            //显示在scrollview里面
            [weakSelf.qcodeView setObject:APP_CONTEXT.shoppingCartManager.scanProductsCart];
            [weakSelf updateScanProduct];
        }else{
            [[iToast makeText:message] show];
        }
    }];

   }

- (void)updateScanProduct{
    //如果这个人登录了 就update一下
    if (APP_CONTEXT.accountManager.accountInfo.token.length > 0) {
        //转换数组
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];
        for (EFSepecialItem *item in APP_CONTEXT.shoppingCartManager.scanProductsCart) {
            NSDictionary *dic = [NSDictionary dictionary];
//            NSString *pId = @"";
//            if (item.id != nil && item.id.length > 0) {
//                pId = item.id;
//            }else{
//                pId = [NSString stringWithFormat:@"%@",item.productId];
//            }
            dic = @{
                    @"id":item.id,
                    @"qty":item.qty,
                    @"barcode":item.barcode != nil ? item.barcode : @""
                    };
            [array addObject:dic];
        }
        
        [APP_CONTEXT.net updateCartList:array total:[NSNumber numberWithUnsignedInteger:APP_CONTEXT.shoppingCartManager.scanProductsCart.count] type:[NSNumber numberWithInt:1] OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
            if (code != 0) {
                [[iToast makeText:message] show];
            }
        }];
    }

}

- (NSDictionary *)dictionaryWithJSON:(id)json {
    if (!json || json == (id)kCFNull) return nil;
    NSDictionary *dic = nil;
    NSData *jsonData = nil;
    if ([json isKindOfClass:[NSDictionary class]]) {
        dic = json;
    } else if ([json isKindOfClass:[NSString class]]) {
        jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding];
    } else if ([json isKindOfClass:[NSData class]]) {
        jsonData = json;
    }
    if (jsonData) {
        dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
        if (![dic isKindOfClass:[NSDictionary class]]) dic = nil;
    }
    return dic;
}


- (void)shopCart{
    if (APP_CONTEXT.accountManager.accountInfo.token.length > 0) {
        EFShoppingCartViewController *shopcart = [[EFShoppingCartViewController alloc] initWithType:1];
        [ICNavigator pushViewController:shopcart animated:YES];
    }else{
        [ICNavigator openLoginWithCompleteBlock:^{
            //登录后  商城type=0 sync
            
        }];
    }
   }

- (void)dealloc{
    self.movePlateQueue = nil;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void)getShopCartData{
    int type = 0; //商城
    [APP_CONTEXT.net getCartListWithIsLocalDelivery:APP_CONTEXT.isLocalDelivery whCode:APP_CONTEXT.whCode type:type OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        if (code == 0) {
            NSArray *list = [info valueForKey:@"list"];
            [APP_CONTEXT.shoppingCartManager.storeProductsCart removeAllObjects];
            if (list.count != 0  ) {
                for (NSDictionary *dic in list) {
                    EFShoppingCartItem *item = [EFShoppingCartItem yy_modelWithDictionary:dic];
                    item.type = [NSNumber numberWithInteger:type];
                    [APP_CONTEXT.shoppingCartManager addToStoreProduct:[item castToSpecialItem ]];
                }
            }
        }
    }];
    type = 1; //快速扫描
    [APP_CONTEXT.net getCartListWithIsLocalDelivery:APP_CONTEXT.isLocalDelivery whCode:APP_CONTEXT.whCode type:type OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        if (code == 0) {
            NSArray *list = [info valueForKey:@"list"];
            [APP_CONTEXT.shoppingCartManager.scanProductsCart removeAllObjects];
            if (list.count != 0  ) {
                for (NSDictionary *dic in list) {
                    EFShoppingCartItem *item = [EFShoppingCartItem yy_modelWithDictionary:dic];
                    item.type = [NSNumber numberWithInteger:type];
                    [APP_CONTEXT.shoppingCartManager addToScanProduct:[item castToSpecialItem ]];
                }
                
            }
             [self.qcodeView setObject:APP_CONTEXT.shoppingCartManager.scanProductsCart];
        }
    }];
}



@end
